package com.project.controller;

import com.alibaba.fastjson.JSON;
import com.project.exception.BusinessException;
import com.project.pojo.*;
import com.project.service.AdminService;
import com.project.service.TeacherService;
import com.project.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;

@Controller
public class LoginController {
    @Autowired
    private UserService userService;

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private AdminService adminService;

    /**
     * 登陆方法
     *
     * @throwGetervletException
     * @throws IOException
     */
    @PostMapping("/login")
    @ResponseBody
    public Response login(@RequestBody LoginUser loginUser) throws BusinessException {
        String username = loginUser.getUsername();
        String password = loginUser.getPassword();
        int role = loginUser.getRole();
        //判断用户类别
        String login = null;
        switch (role) {
            case 1:
                // 管理员 执行管理员登录
                login = adminLogin(username, password);
                break;
            case 2:
                //学生用户 执行学生登陆
                login = userLogin(username, password);
                break;
            case 3:
                // 教职工登录
                login = teacherLogin(username, password);
                break;
            default:
                throw new BusinessException("用户不存在~~");
        }
        return Response.ok("loginSuccess");
    }

    /**
     * 管理员登陆方法
     */
    public String adminLogin(String username,String password) throws BusinessException {
        // 查询管理员用户
        Admin admin = adminService.login(username, password);
        if (admin != null) {
            //登陆成功 把用户信息放到前端
            System.out.println(admin.getRelName()+"登录~~");
            return JSON.toJSONString(admin);
        }else {
            throw new BusinessException("用户不存在~~");
        }
    }

    /**
     * 学生用户登陆方法
     */
    public String userLogin(String username, String password) throws BusinessException {
        // 查询学生用户登录
        User user = userService.login(username, password);
        if (user != null) {
            System.out.println(user.getRelName()+"登录~~");
            //登陆成功 把用户信息放到前端
            return JSON.toJSONString(user);
        }else {
            throw new BusinessException("用户不存在~~");
        }
    }

    /**
     * 教师登陆方法
     */
    public String teacherLogin(String username,String password) throws BusinessException {
        // 查询教职工登录
        Teacher teacher = teacherService.login(username, password);

        if (teacher != null) {
            System.out.println(teacher.gettName() + "登录~~");
            //登陆成功 把用户信息放到前端
            return JSON.toJSONString(teacher);
        } else {
            throw new BusinessException("用户不存在~~");
        }
    }
}

